package org.ocean.online.sys;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.ocean.online.utils.UserUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class DbGuardFactory {

	static Map<String,DbGuard> guardList = new HashMap<String,DbGuard>();
	static Map<String,DataSource> dsList = new HashMap<String,DataSource>();
	
	public static DbGuard getDbGuard(String username){
		Map user = new HashMap();
		user.put("username", username);
		return getDbGuard(user);
	}
	public static DbGuard getDbGuard(Map user){
		String username = user.get("username").toString();
		if(guardList.containsKey(username)){
			return guardList.get(username);
		}
		
		
//		SQLiteDataSource datasource = new SQLiteDataSource();
//		datasource.setUrl("jdbc:sqlite:"+UserUtil.getDbSpace(username)+username+".db");
		
//		DriverManagerDataSource datasource=new DriverManagerDataSource ();
//		datasource.setDriverClassName("org.hsqldb.jdbcDriver");
//		datasource.setUrl("jdbc:hsqldb:file:"+UserUtil.getDbSpace(username)+username+".hsqldb");
		DriverManagerDataSource datasource=new DriverManagerDataSource ();
		if("mutiple".equals(OnlineConfig.getProperty("projectType"))){
			datasource.setDriverClassName("org.h2.Driver");
//			datasource.setUrl("jdbc:h2:file:"+UserUtil.getDbSpace(username)+username+";MODE=MYSQL");
			datasource.setUrl("jdbc:h2:file:"+UserUtil.getDbSpace(username)+username);
		}else{
			datasource.setDriverClassName("org.h2.Driver");
			datasource.setUrl(OnlineConfig.getProperty("url"));
		}
		
		
//		DriverManagerDataSource datasource=new DriverManagerDataSource ();
//		datasource.setUrl("jdbc:derby:e:\\derbydata\\"+user.get("username")+".db;create=true");
		
//		MysqlDataSource datasource=new MysqlDataSource ();
//		datasource.setUrl("jdbc:mysql://localhost:3306/"+user.get("username"));
//		datasource.setUser("root");
//		datasource.setPassword("admin");
		
//		String url = "jdbc:Access:///e:\\dbspace\\"+user.get("username")+".mdb";
//		DriverManagerDataSource datasource=new DriverManagerDataSource ();
//		datasource.setUrl(url);
//		datasource.setDriverClassName("com.hxtt.sql.access.AccessDriver");
		
		dsList.put(user.get("username").toString(), datasource);
		DbGuard guard = new DbGuard(datasource);
		//guard.jt = new JdbcTemplate(datasource);
		guard.transactionManager = new DataSourceTransactionManager(datasource);
		guardList.put(user.get("username").toString(), guard);
		return guard;
	}
	
	public static DataSource getDataSource(String username){
		return dsList.get(username);
	}
}
